import { SRMQTTDeviceAlert, SRMQTTString } from "../model/sr.model";
import { V3proSubjectMessage } from "../../v3pro-task/model/v3pro.model";
import { srProtoBufDeviceAlert, srProtoBufString } from "../../../configs/env.config.load";
import { cond, curry } from "ramda";
import { V3proSubjectMessageTypeEnum } from "../../v3pro-task/model/v3pro.enum";

/**
 * 转换消息为 SRMQTTDeviceAlert
 */
export class ToSRMqttConverter {
  /**
   * 从 V3proSubjectMessage 转换消息为 Buffer
   * @param message
   */
  static fromV3proSubjectMessage(message: V3proSubjectMessage): Buffer {
    const equalsMsgType = curry(
      (type: V3proSubjectMessageTypeEnum, message: V3proSubjectMessage) => {
        return message.msgType === type;
      },
    );
    return cond([
      [equalsMsgType(V3proSubjectMessageTypeEnum.ALERT), ToSRMqttConverter.fromV3proAlertMessage],
      [equalsMsgType(V3proSubjectMessageTypeEnum.STRING), ToSRMqttConverter.fromV3proStringMessage],
    ])(message);
  }

  /**
   * 从 V3proAlertMessage 转换消息为 SRMQTTDeviceAlert
   * @param message
   */
  static fromV3proAlertMessage(message: V3proSubjectMessage): Buffer {
    const srMessage = new SRMQTTDeviceAlert();
    if (message.files && message.files.length > 0) {
      srMessage.description = JSON.stringify({
        files: message.files.map(({ id, type }) => ({ id, type })),
      });
    }
    srMessage.value = message.value;
    srMessage.timestamp = new Date().toISOString();
    srMessage.threshold = message.threshold;
    srMessage.status = message.status;
    return Buffer.from(srProtoBufDeviceAlert.encode(srMessage).finish());
  }

  static fromV3proStringMessage(message: SRMQTTString): Buffer {
    const srMessage = new SRMQTTString();
    srMessage.param = message.param;
    console.log(srMessage);
    return Buffer.from(srProtoBufString.encode(srMessage).finish());
  }
}
